# -*- coding: utf-8 -*-
'''
Created on 2013-5-8

@author: yq
'''
from Common.htmlHlep import Find
from Common.tool import tool
from Cms.plus import  page,user
import  hashlib,datetime
from Models import  models
from django.db import transaction
from Cms import config

def Initialization(request):
        '''
                     登录页
        '''
        if len(models.Sys_Info.objects.filter())!=0:
                return Find.Redirect("/AdminMain/Home/Login")
        
        return Find.View(request)


def Edit(request):
        sys_Info=models.Sys_Info.objects.filter()[0]
       
        return Find.View(request,sys_Info)

def DoEdit(request):
        try:
            info = models.Sys_Info(WebId=request.POST.get("WebId"))
            Find.UpdateModel(request,info)
            
            info.save()
        except:
            return Find.JsonX(True,"初始化失败")
            
        return Find.JsonX(False,"添加成功")


@transaction.commit_manually 
def DoInitialization(request):
        try:
            if len(models.Sys_Info.objects.filter())!=0:
                transaction.rollback()
                return Find.JsonX(True, "已初始化，请直接访问登录页面")
            
            info = models.Sys_Info(WebId=tool.guid())
            Find.UpdateModel(request,info)
            
            #注册账号
            account = models.User_Account(State=1,TypeId=0,
                                   UserId=tool.guid(),
                                   CreateTtime=datetime.datetime.now(),
                                   PurviewTeamID=models.Sys_Team.objects.get(id=3))
            Find.UpdateModel(request,account)
            
            #注册登录账号
            login = models.User_Login(Rowid=tool.guid(),
                                      UserId=account,State=1,
                                      Types=0,
                                      CreateTtime=datetime.datetime.now())
            Find.UpdateModel(request,login)
            login.PassWord=tool.Md5(login.PassWord)
            
            if 0!=len(models.User_Account.objects.filter(NickName=account.NickName)):
                transaction.rollback()
                return Find.JsonX(True, "昵称已存在")
            
            if 0!=len(models.User_Login.objects.filter(Account=login.Account)):
                transaction.rollback()
                return Find.JsonX(True, "账号已存在")
            config.Config().SetAdminId(account.UserId)
            info.save()
            account.save()
            login.save()
            transaction.commit()
        except:
            transaction.rollback()
            return Find.JsonX(True,"初始化失败")
            
        return Find.JsonX(False,"添加成功")